<template>
  <!-- 8席位网格布局 -->
  <div class="grid grid-cols-4 gap-4 p-4">
    <!-- 本地用户 -->
    <div v-if="localTracks" class="border rounded-lg overflow-hidden">
      <video ref="localVideo" class="w-full h-48 object-cover"></video>
      <div class="p-2 bg-gray-100">
        <button class="btn" @click="toggleLocalAudio">
          {{ localAudioEnabled ? "静音" : "取消静音" }}
        </button>
      </div>
    </div>

    <!-- 远程用户 -->
    <div v-for="user in remoteUsers" :key="user.uid" class="border rounded-lg overflow-hidden">
      <video :ref="setRemoteVideo" class="w-full h-48 object-cover"></video>
      <div class="p-2 bg-gray-100">
        <button class="btn" @click="toggleRemoteAudio(user)">
          {{ user.audioEnabled ? "静音" : "取消静音" }}
        </button>
      </div>
    </div>
  </div>

  <!-- 创建房间 -->
  <div class="p-4">
    <button v-if="!isJoined" class="btn-primary" @click="createRoom">创建新房间</button>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import AgoraRTC from "agora-rtc-sdk-ng";

// 声网配置（需替换实际参数）
const appId = "4487c53bb8a548508ffe17fceb321334";
const token =
  "007eJxTYJj/QiIoqXj2F/fdUZ+W5m5gS5+llsVtO+XHtaiTc19s7vNUYDAxsTBPNjVOSrJINDWxMDWwSEtLNTRPS05NMjYyNDY2mR99K70hkJHhvnY8IxMDIxiC+CwMhkbGhgwMTGgiAKz2IWk=";

// 响应式数据
const localTracks = ref(null);
const remoteUsers = ref([]);
const isJoined = ref(false);
const client = ref(null);

// 初始化客户端
const initClient = () => {
  client.value = AgoraRTC.createClient({ mode: "rtc", codec: "vp8" });
  setupEventListeners();
};

// 事件监听
const setupEventListeners = () => {
  client.value.on("user-published", async (user, mediaType) => {
    await client.value.subscribe(user, mediaType);
    if (mediaType === "audio") {
      user.audioTrack.play();
    }
    updateRemoteUsers(user);
  });

  client.value.on("user-unpublished", (user) => {
    remoteUsers.value = remoteUsers.value.filter((u) => u.uid !== user.uid);
  });
};

// 创建房间
const createRoom = async () => {
  // const channelName = `room_${Date.now()}`
  await client.value.join(appId, "1231", token, "123456");
  await publishLocalTracks();
  isJoined.value = true;
};

// 发布本地轨道
const publishLocalTracks = async () => {
  const [micTrack, camTrack] = await AgoraRTC.createMicrophoneAndCameraTracks();
  localTracks.value = { audioTrack: micTrack, videoTrack: camTrack };
  await client.value.publish([micTrack, camTrack]);
  camTrack.play("localVideo");
};

// 控制远程用户音频
const toggleRemoteAudio = (user) => {
  user.audioEnabled = !user.audioEnabled;
  user.audioTrack.setEnabled(user.audioEnabled);
};

// 控制本地音频
const toggleLocalAudio = () => {
  localTracks.value.audioTrack.setEnabled(!localTracks.value.audioTrack.enabled);
};

// 初始化
onMounted(initClient);

// 清理资源
onBeforeUnmount(async () => {
  if (client.value) {
    await client.value.leave();
    localTracks.value?.forEach((track) => track.stop());
  }
});
</script>

<style>
/* 自定义样式 */
.btn {
  @apply px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600;
}

.btn-primary {
  @apply bg-green-500 hover:bg-green-600;
}

.grid {
  @apply max-w-6xl mx-auto;
}
</style>
